package com.jwt_demo.jwt_demo.util;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    // 1. 创建JWT的签名密钥
    private static String sign = "admin";

    // 生成JWT的方法
    public static String generateToken(long expirationMillis, String userName, String role) {

        // 2. 设置JWT的构建器
        long nowMillis = System.currentTimeMillis();
        Date expiration = new Date(nowMillis + expirationMillis);

        // 3. 构建JWT并返回
        String jwt = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", SignatureAlgorithm.HS256)
                .claim("username", userName)
                .claim("role", role)
                .setSubject("admin-test")
                .setExpiration(expiration)
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, sign)
                .compact();

        return jwt;
    }

    // 验证JWT的有效性
    public static boolean validateToken(String token) {
        try {
            boolean signed = Jwts.parser().isSigned(token);
            return signed;
        } catch (Exception e) {
            return false;
        }
    }

    // 解析JWT的方法
    public static Claims parseToken(String token) {

        // 2. 解析JWT
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(sign).parseClaimsJws(token);
        Claims body = claimsJws.getBody();

        //String username = body.get("username").toString();

        // 3. 获取JWT中的声明
        return body;
    }

}
